/**
 * 76. 最小覆盖子串
 * https://leetcode-cn.com/problems/minimum-window-substring/
 */

function isComplete(map) {
  // eslint-disable-next-line no-restricted-syntax
  for (const [, count] of map) {
    if (count > 0) return false;
  }
  return true;
}

/**
 * @param {string} s
 * @param {string} t
 * @return {string}
 */
function minWindow(s, t) {
  const map = new Map();
  const { length: lengthT } = t;
  for (let i = 0; i < lengthT; i += 1) {
    const code = t.charCodeAt(i);
    map.set(code, (map.get(code) || 0) + 1);
  }
  let p = -1;
  let minLen = Number.MAX_SAFE_INTEGER;
  let minStr = '';
  const { length: lengthS } = s;
  for (let i = 0; i < lengthS; i += 1) {
    const code1 = s.charCodeAt(i);
    if (map.has(code1)) {
      if (p < 0) p = i;
      map.set(code1, map.get(code1) - 1);
      while (p < i) {
        const code2 = s.charCodeAt(p);
        if (map.has(code2)) {
          const count2 = map.get(code2);
          if (count2 < 0) {
            map.set(code2, count2 + 1);
          } else {
            break;
          }
        }
        p += 1;
      }
      if (isComplete(map)) {
        const len = i - p + 1;
        if (len < minLen) {
          minLen = len;
          minStr = s.substring(p, i + 1);
        }
      }
    }
  }
  return minStr;
}

console.log(minWindow('ADOBECODEBANC', 'ABC'));
console.log(minWindow('a', 'a'));
console.log(minWindow('a', 'aa'));
console.log(minWindow('aaaaaaaaaaaabbbbbcdd', 'abcdd'));
